package xyz.lwm.lazycat.netpipe.service.impl;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import org.mindrot.jbcrypt.BCrypt;
import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.netpipe.domain.entity.User;
import xyz.lwm.lazycat.netpipe.mapper.UserMapper;
import xyz.lwm.lazycat.netpipe.service.UserService;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.web.annocation.Service;

/**
 * @author lwm
 */
@Service
class UserServiceImpl implements UserService {

    @Inject
    private UserMapper userMapper;

    @Override
    public BaseMapper<User> getMapper() {
        return userMapper;
    }

    @Override
    public User getByUsername(String username) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(User::getUsername).eq(username);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean save(User entity) {
        It.of(entity.getPassword()).let(this::hashpw).also(entity::setPassword);
        return UserService.super.save(entity);
    }

    @Override
    public boolean updateById(User entity) {
        It.of(entity.getPassword()).let(this::hashpw).also(entity::setPassword);
        return UserService.super.updateById(entity);
    }

    /**
     * 密码加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String hashpw(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }

}
